package com.chr.hongyun.exception;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 精简全局异常
 * 创建时间:2023/4/14
 * 创建人:陈浩然
 */
@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public String exceptionHandler(Exception e) {
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
            return exception.getBindingResult().getFieldError().getDefaultMessage();//获取具体的异常消息
        } else if (e instanceof HongyunException) {
            HongyunException exception = (HongyunException) e;
            return exception.getMsg();
        } else if (e instanceof UnauthorizedException) {
            return "你不具备相关权限";
        } else if (e instanceof RuntimeException) {
            RuntimeException exception = (RuntimeException) e;
            return exception.getMessage();
        } else {
            return "后端执行错误";
        }
    }
}
